package api

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"net/http"
	"oidc/dao"
	"oidc/model"
	"oidc/util"
)

func ReturnCode() gin.HandlerFunc { //把认证成功把code重定向回依赖方
	return func(c *gin.Context) {
		var req model.AuthorizationRequest
		req.ResponseType = c.Query(util.GetCode(util.RESPONSE_TYPE))
		req.ClientId = c.Query(util.GetCode(util.CLIENT_ID))
		req.State = c.Query(util.GetCode(util.STATE))
		req.RedirectUrl = c.Query(util.GetCode(util.REDIRECT_URL))
		req.Scope = c.Query(util.GetCode(util.SCOPE))

		var client model.Client
		client.ClientID = req.ClientId
		client.RedirectUrl = req.RedirectUrl
		if !dao.IFClientIDRight(client) {
			c.JSON(200, gin.H{
				"status": false,
				"data":   "parm is not right",
			})
			return
		}
		//这里假设用户认证并授权成功了
		code := dao.HandUUID(uuid.New().String())
		userinfo := userAuthorization(req.ClientId, code)
		//存储code和其对应的user信息
		dao.StoreCodeDB(userinfo)
		//向依赖方返回code
		if req.Scope == "" {
			http.Get(req.RedirectUrl + "&code=" + code)
			//c.Redirect(301, req.RedirectUrl+"&code="+code)
		} else {
			http.Get(req.RedirectUrl + "&scope=" + req.Scope + "&code=" + code)
			//c.Redirect(301, req.RedirectUrl+"&scope="+req.Scope+"&code="+code)
		}
		c.JSON(200, gin.H{
			"code": code,
		})
		//10min后code未使用就删除code
		go dao.WaitCodeDel(code)
	}
}

func userAuthorization(clientId, code string) (auth model.UserAuth) { //假装用户认证咯
	auth.UserInfo = dao.GetUser("10000000")
	auth.ClientId = clientId
	auth.Code = code
	return
}
